const app = getApp()
import {
  Config
} from '../../utils/config.js';
const {
  MemberModel
} = require('../../utils/member-model.js');
var memberModel = new MemberModel();
const {
  decodeGPS
} = require('../../utils/decodeGPS.js')
const {
  MarketingModel
} = require('../../utils/marketing-model.js');
const {
  getPx,
  getWinHei
} = require('../../utils/util.js');
var marketingModel = new MarketingModel();
const {
  CurrencyShopModel
} = require('../../utils/currencyshop-model.js')
const currencyShopModel = new CurrencyShopModel()
const {
  SvipModel
} = require('../../utils/svip-model.js')
var svipModel = new SvipModel()
const {
  ActivityModel
} = require('../../utils/activity-model.js')
var activityModel = new ActivityModel()
const {
  getDistance
} = require('../../utils/util.js')
Page({
  data: {
    hasAssets: null,
    curShopClose: false,
    memberTransferRelation: null,
    swiperImages: [
      'https://oss.kiscloud.net/wechat/images/swiper1.png',
      'https://oss.kiscloud.net/wechat/images/swiper2.png',
      'https://oss.kiscloud.net/wechat/images/swiper3.png',
      'https://oss.kiscloud.net/wechat/images/swiper4.png'
    ],
    shopClosePad: 0,
    shopCloseHei: 0,
    dialogShow: false,
    giftbagShow: false, //扫码礼包
    debrisShow: false, //扫码碎片
    gatherShow: false, //去点亮
    errorbagShow: false, //错误提示
    debrisData: {}, //碎片列表
    activityInfo: {}, //点亮详情
    authShow: false, //登录按钮
    authShow1: false, // 链接授权
    svipShow: false, //svip入口
    coupons: [],
    code: '', //扫码结果
    shop: {},
    navigationHeight: 64,
    navigationTop: 26,
    navigationLeft: 10,
    capsuleWidth: 87,
    menus: [],
    holdMenus: [],
    activeIdx: 0,
    modules: [],
    showType: false, //显示类型
    merchantId: '',
    defaultCurrent: 0,
    currentBannerIndex: 0,
    currentCommonIndex: 0,
    appletMobile: '',
    activityError: '', //活动错误提示
    merchant: '',
    giftNeedLogin: '0',
    encryptedData: '',
    iv: '',
    isShowLoading: false, //是否运行loding弹出层
    cardActivityId: '',
    bargainId: null,
    isBargain: true
  },
  onLoad(options) {
    const query = options || {}
    const coupons = JSON.parse(query.registerGifts || '[]')
    app.getInfo().then(res => {
      this.setData({
        appletMobile: res.data.appletMobile || '',
        merchant: res.data.merchantId
      })
      // 小程序卡片需要授权登录
      if (options.source == 2 && !res.data.login) {
        wx.showModal({
          title: '提示',
          content: '去登录',
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/login/index'
              })
            }
          }
        })
      }
      this.getMenu(res.data.merchantId)
      this.getShopInfo(res.data.merchantId)
    })
    this.setData({
      dialogShow: !!coupons.length,
      giftNeedLogin: options.giftNeedLogin || '0',
      encryptedData: options.encryptedData || '',
      iv: options.iv || '',
      coupons
    })
    const navigationBtnObj = wx.getMenuButtonBoundingClientRect()
    wx.getSystemInfo({
      success: res => {
        this.setData({
          navigationHeight: res.statusBarHeight + navigationBtnObj.height + (navigationBtnObj.top - res.statusBarHeight) * 2,
          navigationTop: navigationBtnObj.top,
          navigationLeft: res.windowWidth - navigationBtnObj.right,
          capsuleWidth: navigationBtnObj.width
        })
        this.setData({
          shopClosePad: this.data.navigationHeight + getPx(50),
          shopCloseHei: res.windowHeight - (this.data.navigationHeight + getPx(50)) - getPx(150)
        })
      }
    })
  },
  getModule(merchantId, shopId, brandId) {
    this.getBargainActivity(merchantId, shopId)
    currencyShopModel.queryHomeModule({
      merchantId,
      shopId,
      brandId,
      moduleTypes: [1, 2, 3, 4, 5]
    }).then(data => {
      data.modules.forEach(moduleItem => {
        if (moduleItem.moduleType == 4) {
          moduleItem.contents.forEach(item => {
            const options = item.options
            if (options.goodsPrices) {
              options.goodsPrices.forEach(goods => {
                const price = goods
                const split = Number(goods.amount).toFixed(2).split('.')
                price.int = split[0]
                price.float = split[1]
              })
            }
            options.satisfyActivityTypeList = options.satisfyActivityTypeList || []
            if (options.rightsType === 1 || !options.satisfyActivityTypeList.length) {
              options.satisfyActivityTypeList = []
            } else if (options.satisfyActivityTypeList.length === 1) {
              options.satisfyActivityTypeList = options.satisfyActivityTypeList
            } else if (options.satisfyActivityTypeList.length === 2 && options.satisfyActivityTypeList.includes(7) && options.satisfyActivityTypeList.includes(8)) {
              options.satisfyActivityTypeList = [8]
            } else {
              options.satisfyActivityTypeList = [5]
            }
          })
        } else if (moduleItem.moduleType == 1) {
          const i_contents = moduleItem.contents
          moduleItem.contents = []
          i_contents.forEach(item => {
            if (item.options.jumpUrl != '/activityBargain/bargain/productList/index') {
              moduleItem.contents.push(item)
            } else if (item.options.jumpUrl == '/activityBargain/bargain/productList/index' && this.data.bargainId) {
              item.options.jumpUrl = '/activityBargain/bargain/productList/index?activityId=' + this.data.bargainId
              moduleItem.contents.push(item)
            }
          })
        }
      })
      this.setData({
        currentBannerIndex: 0,
        currentCommonIndex: 0,
        defaultCurrent: 0,
        modules: data.modules
      })
      if (!this.data.isShowLoading) {
        wx.hideLoading()
        this.setData({
          isShowLoading: false
        })
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },
  getMenu(merchantId) {
    currencyShopModel.queryMenu({
      merchantId,
      moduleTypes: [6]
    }).then(data => {
      const menus = data.modules[0].contents.filter(item => {
        return item.options.nav_type == '1'
      })
      const holdMenus = data.modules[0].contents.filter(item => {
        return item.options.nav_type == '2'
      })
      let activeIdx = 0
      menus.forEach((item, index) => {
        if (item.options.nav_redirect_type == '1') {
          activeIdx = index
        }
      })
      this.setData({
        menus,
        activeIdx,
        holdMenus
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },
  currentBannerChange(e) {
    this.setData({
      currentBannerIndex: e.detail.current
    })
  },
  currentCommonChange(e) {
    this.setData({
      currentCommonIndex: e.detail.current
    })
  },
  jumpShop(e) {
    const {
      item
    } = e.currentTarget.dataset
    if (item.need_authorize == '1' && !app.globalData.isLogin) {
      this.setData({
        authShow1: true
      })
    } else {
      wx.navigateTo({
        url: item.link
      })
    }
  },
  goGoodsDetail(e) {
    const {
      options
    } = e.currentTarget.dataset
    // type暂时只有游戏币固定为0 从首页进入商品详情页entrance为0
    wx.navigateTo({
      url: `/pages/currencyShop/currencyDetail/index?shopName=${this.data.shop.shopName}&currency=${encodeURIComponent(JSON.stringify(options))}&shopId=${this.data.shop.shopId}&type=${0}&entrance=${0}`
    })
  },
  clickBannerItem(e) {
    wx.reportAnalytics('home_banner')
    const options = e.currentTarget.dataset.options || {}
    if (options.jumpType == 1) {
      if (options.jumpUrl) {
        let merchantId = wx.getStorageSync('merchantId')
        if (options.jumpUrl.indexOf('activityBargain/bargain/productList/index') > -1) {
          let param = {
            activityId: this.data.bargainId,
            source: '点击进入砍价专区'
          }
          app.setTrackerLog(merchantId, 1, 4, 2, param)
        } else if (options.jumpUrl.indexOf('activityBargain/giftBag/home/index') > -1) {
          let param = {
            source: 'banner'
          }
          app.setTrackerLog(merchantId, 2, 4, 2, param)
        }
        let goUrl = '';
        if (options.jumpUrl.indexOf('?') > -1) {
          goUrl = `${options.jumpUrl}&shopId=${this.data.shop.shopId}&shopName=${this.data.shop.shopName}&cityCode=${this.data.shop.cityCode}&cityName=${this.data.shop.cityName}`
        } else {
          goUrl = `${options.jumpUrl}?shopId=${this.data.shop.shopId}&shopName=${this.data.shop.shopName}&cityCode=${this.data.shop.cityCode}&cityName=${this.data.shop.cityName}`
        }
        wx.navigateTo({
          url: goUrl
        })
      }
    } else if (options.jumpType == 2) {
      wx.navigateToMiniProgram({
        appId: options.jumpAppId,
        path: options.jumpUrl || 'pages/index/index',
        extraData: {},
        envVersion: 'release',
        success(res) {}
      })
    } else if (options.jumpType == 3) {
      if (options.jumpUrl) {
        wx.navigateTo({
          url: `/pages/h5/index?url=${encodeURIComponent(`${options.jumpUrl}?phoneNumber=${this.data.appletMobile}`)}`,
        })
      }
    }
  },
  goScanCode() {
    wx.reportAnalytics('page_qrcode_enter');
    wx.reLaunch({
      url: '/pages/memberCenter/QRCode/index'
    })
  },
  goHotList(e) {
    const options = e.currentTarget.dataset.options || {}
    if (options.link) {
      wx.navigateTo({
        url: options.link
      })
    }
  },
  goGameList(e) {
    const options = e.currentTarget.dataset.options || {}
    if (options.content_more_link) {
      wx.navigateTo({
        url: options.content_more_link
      })
    }
  },
  goContent(e) {
    const options = e.currentTarget.dataset.options || {}
    if (options.redirect_type == '1') {
      wx.navigateToMiniProgram({
        appId: options.app_id,
        path: options.link || 'pages/index/index',
        extraData: {},
        envVersion: 'release',
        success(res) {}
      })
    } else if (options.redirect_type == '0' && options.link) {
      wx.navigateTo({
        url: options.link
      })
    }
  },
  goMiniAppPet() {
    wx.reportAnalytics('home_pet')
    wx.navigateToMiniProgram({
      appId: 'wxf5e80f46fe65dadc',
      path: 'pages/index/index',
      extraData: {},
      envVersion: 'release',
      success(res) {}
    })
  },
  goMiniAppCgl() {
    wx.reportAnalytics('home_banner_bottom')
    wx.navigateToMiniProgram({
      appId: 'wx8ead130ae24508a8',
      path: 'pages/index/index',
      extraData: {},
      envVersion: 'release',
      success(res) {}
    })
  },
  //去兑奖台兑换
  goExchange() {
    var that = this;
    that.setData({
      gatherShow: false
    }, function () {
      if (that.data.activityInfo.activityType == 1) { //活动类型  1:老集卡 2:全国集卡（抽奖券） 3:达人机（幸运福袋）
        wx.redirectTo({
          url: `/pages/memberCenter/prize/prizeCancellation/index?activityVerificationId=${that.data.activityInfo.activityVerificationId}`
        })
      }
    })
  },
  goCurrencyShop() {
    // this.judgeIsLogin('/pages/currencyShop/chooseStore/index')
    const shop = this.data.shop
    wx.navigateTo({
      url: `/pages/currencyShop/chooseCurrency/index?shopName=${shop.shopName}&address=${shop.address || ''}&shopId=${shop.shopId}`
    })
  },
  goSelectShop() {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userLocation']) {
          wx.reportAnalytics('home_currency')
          const shop = this.data.shop
          wx.navigateTo({
            url: `/pages/currencyShop/chooseStore/index?cityCode=${shop.cityCode}&cityName=${shop.cityName}&shopId=${shop.shopId}`
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '没有授权定位信息，打开设置',
            success(res) {
              if (res.confirm) {
                wx.openSetting()
              }
            }
          })
        }
      }
    })
  },
  goIntegralShop() {
    wx.reportAnalytics('home_integral')
    // this.judgeIsLogin('/pages/integralShop/integralGoods/index')
    wx.navigateTo({
      url: '/pages/integralShop/integralGoods/index'
    })
  },
  closeDialog() {
    this.setData({
      dialogShow: false
    })
    wx.reportAnalytics('newcomer_close')
  },
  //关闭大礼包
  closeGiftbag() {
    var that = this;
    that.setData({
      giftbagShow: false
    }, function () {
      if (that.data.debrisData.isMissFragment) {
        that.setData({
          debrisShow: true
        })
      }
    })
  },
  //碎片集合
  closeDebris() {
    this.setData({
      debrisShow: false
    })
  },
  //去点亮
  closeIllume() {
    var that = this;
    that.setData({
      debrisShow: false,
      gatherShow: false
    })
  },
  //去点亮
  goIllume() {
    var that = this;
    that.setData({
      debrisShow: false,
    }, function () {
      that.getMemberLight();
    })
  },
  //福袋
  closeErrorbag() {
    this.setData({
      errorbagShow: false,
    })
  },
  /**
   * 扫码
   * */
  scanQRCode: function () {
    var that = this;
    wx.scanCode({
      success(res) {
        that.setData({
          code: res.result
        }, function () {
          if (app.globalData.isLogin) {
            that.getMemberDraw();
          } else {
            var parameter = ''
            if (that.data.code.indexOf('?') > -1) {
              let param = that.data.code.split("?");
              parameter = param[1].split("/");
            } else {
              parameter = that.data.code.split("/");
            }
            marketingModel.getCardActivityId({
              merchantId: parameter[0] || '',
              qrCodeMsg: res.result
            }).then(data => {
              that.setData({
                authShow: true,
                cardActivityId: data
              })
            }).catch(err => {
              wx.showToast({
                title: `${err.error}`,
                icon: 'none',
                duration: 2000
              })
            })
          }
        })
      },
      fail(res) {
        wx.showToast({
          title: `扫码失败`,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  /**
   * 会员扫码抽奖
   */
  getMemberDraw: function () {
    app.getInfo().then(({
      data
    }) => {
      var that = this;
      var parameter = ''
      if (that.data.code.indexOf('?') > -1) {
        let param = that.data.code.split("?");
        parameter = param[1].split("/");
      } else {
        parameter = that.data.code.split("/");
      }
      var param = {};
      param.merchantId = parameter[0] || ""; //商户id
      param.activityCardDetailId = parameter[1] || ""; //卡片id
      param.phoneNumber = data.appletMobile;
      if (param.merchantId && param.activityCardDetailId) {
        if (param.merchantId === this.data.merchant) {
          marketingModel.memberDraw(param).then(data => {
            if (data) {
              that.setData({
                debrisData: data,
                giftbagShow: true
              });
            } else {
              that.setData({
                debrisData: {},
                giftbagShow: false
              });
            }
          }).catch(err => {
            if (err.status == '400') {
              that.setData({
                errorbagShow: true,
                activityError: err.error
              })
            } else {
              wx.showToast({
                title: `${err.error}`,
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else {
          wx.showToast({
            title: '卡片不存在',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  /**
   * 去点亮
   */
  getMemberLight: function () {
    var that = this;
    var item = that.data.debrisData.activityAward;
    var param = {};
    param.merchantId = item.merchantId; //商户id
    param.activityAwardId = item.activityAwardId; //奖品id
    marketingModel.memberLight(param).then(data => {
      if (data) {
        that.setData({
          activityInfo: data,
          gatherShow: true
        });
      } else {
        that.setData({
          activityInfo: {},
          gatherShow: false
        });
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 错误信息
   */
  getAppletIndex() {
    this.baseRestUrl = Config.restUrl + "/applet/index";
    wx.request({
      url: this.baseRestUrl,
      data: {},
      method: 'post',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var code = res.statusCode.toString();
        if (code == '503') {
          wx.reLaunch({
            url: '/pages/error/index'
          })
        }
      },
      fail: function (err) {}
    });
  },
  onShow() {
    this.getAppletIndex();
  },
  getShopInfo(merchantId) {
    wx.login({
      success: ({
        code
      }) => {
        if (!this.data.isShowLoading) {
          wx.showLoading({
            title: '加载中',
            mask: true
          });
          this.setData({
            isShowLoading: true
          })
        }
        const shareData = wx.getStorageSync('shareData')
        if (this.data.encryptedData) {
          currencyShopModel.queryShopInfo({
            merchantId,
            shopId: shareData.shopId
          }).then(res => {
            this.jugdePositionNext(merchantId, res)
          })
          currencyShopModel.setUserSelectShop({
            shopId: shareData.shopId,
            code,
            appId: Config.appId,
            merchantId
          })
        } else {
          currencyShopModel.getUserSelectShop({
            merchantId,
            appId: Config.appId,
            code
          }).then(res => {
            const merchantId = res.merchantId
            this.getPreviewVersion(merchantId);
            wx.authorize({
              scope: 'scope.userLocation',
              success: () => {
                if (res.shopInfo) {
                  this.jugdePositionNext(merchantId, res.shopInfo)
                  this.jugdePosition(merchantId, res.shopInfo)
                } else {
                  this.jugdePosition(merchantId, res.shopInfo)
                }
              },
              fail: () => {
                wx.redirectTo({
                  url: '/pages/chooseCity/index'
                })
              }
            })
          })
        }
      }
    })
  },
  jugdePosition(merchantId, shopInfo) {
    decodeGPS().then(res => {
      const {
        addressComponent,
        formatted_address,
        cityCode,
        location
      } = res
      if (cityCode && cityCode !== 'undefined') {
        currencyShopModel.getShops({
          cityCode,
          merchantId,
          limit: 9999,
          offset: 0
        }).then(data => {
          data = data || []
          if (data.length) {
            const shops = data.map(item => {
              const distance = getDistance(location.lat, location.lng, item.latitude, item.longitude) || 0
              return {
                ...item,
                distance
              }
            })
            const result = shops.sort((a, b) => a.distance - b.distance)
            if (shopInfo && result[0].shopId === shopInfo.shopId) {
              this.jugdePositionNext(merchantId, result[0])
            } else {
              // if (wx.getStorageSync('dontExchangeShop')) {
              //   shopInfo && this.jugdePositionNext(merchantId, shopInfo)
              // } else {
                let openShops = result.filter(item => item.statusNew != '已撤店')
                if (openShops.length > 0){
                  wx.showModal({
                    title: '提示',
                    content: `当前定位${openShops[0].shopName}，是否切换？`,
                    cancelText: '不切换',
                    confirmText: '切换',
                    success: (res) => {
                      if (res.confirm) {
                        wx.login({
                          success: ({
                            code
                          }) => {
                            currencyShopModel.setUserSelectShop({
                              shopId: openShops[0].shopId,
                              code,
                              appId: Config.appId,
                              merchantId
                            })
                          }
                        })
                        this.jugdePositionNext(merchantId, openShops[0])
                      } else {
                        // wx.setStorageSync('dontExchangeShop', true)
                      }
                    }
                  })
                }
              // }
            }
          } else if (!shopInfo) {
            wx.redirectTo({
              url: '/pages/chooseCity/index'
            })
          }
        })
      } else {
        wx.showToast({
          title: '定位失败，请重试',
          icon: 'none',
          duration: 2000
        })
      }
    }).catch(err => {
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userLocation']) {
            wx.showToast({
              title: '定位失败',
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    })
  },
  jugdePositionNext(merchantId, shopInfo) {
    this.setData({
      shop: shopInfo,
      memberTransferRelation: shopInfo.memberTransferRelation
    })
    wx.setStorageSync('memberTransferRelation', shopInfo.memberTransferRelation)
    if (shopInfo.memberTransferRelation) {
      memberModel.userShopAsset({
        "merchantId": merchantId,
        "shopId":shopInfo.shopId,
        "memberId": wx.getStorageSync('memberId')
      }).then(res => {
        if (res.coinTotal == 0 && res.gameCouponTotal == 0 && res.timesCardTotal == 0 && res.voucherPackageTotal == 0 && res.lotteryTotal == 0) {
          this.setData({
            hasAssets:false
          })
          wx.setStorageSync('hasAssets', false)
        } else {
          this.setData({
            hasAssets:true
          })
          wx.setStorageSync('hasAssets', true)
        }
      })
    }
    wx.setStorageSync('shopInfo', shopInfo)
    if (shopInfo.statusNew === '已撤店') {
      this.setData({
        curShopClose: true
      })
      return
    } else {
      this.setData({
        curShopClose: false
      })
    }
    this.getBargainActivity(merchantId, shopInfo.shopId)
    this.getModule(merchantId, shopInfo.shopId, shopInfo.brandId)
    this.shopHaveSVip(merchantId, shopInfo.shopId).then(() => {
      this.setData({
        svipShow: true
      })
      wx.setStorageSync('menuHasSvip', true)
    }).catch(() => {
      this.setData({
        svipShow: false
      })
      wx.setStorageSync('menuHasSvip', false)
    })
  },
  gosVip: function () {
    if (app.globalData.isLogin) {
      wx.navigateTo({
        url: `/pages/svip/purchase/index?shopId=${this.data.shop.shopId}`
      })
    }
  },
  goActivity: function () {
    wx.navigateTo({
      url: `/pages/activity/robCoupon/index?merchantId=${this.data.merchantId}`
    })
  },
  shopHaveSVip(merchantId, shopId) {
    return new Promise((resolve, reject) => {
      currencyShopModel.queryProductShelves({
        merchantId,
        shopId
      }).then(res => {
        if (res.svipShelves) {
          resolve(true)
        } else {
          reject(true)
        }
      }).catch(err => {
        reject(true)
      })
    })
  },

  /**
   * 活动入口
   */
  getPreviewVersion(merchantId) {
    let that = this;
    svipModel.previewVersion({
      merchantId: merchantId,
      appId: Config.appId,
    }).then(res => {
      if (res === "coupon_marketing") {
        that.setData({
          showType: false
        })
      } else {
        that.getActivityInstantWhetherShow(merchantId);
      }
    })
  },

  /**
   * banner是否展示
   */
  getActivityInstantWhetherShow(merchantId) {
    let that = this;
    activityModel.activityInstantWhetherShow({
      merchantId: merchantId,
    }).then(res => {
      if (res == 1) {
        that.setData({
          merchantId: merchantId,
          showType: true
        })
      } else {
        that.setData({
          showType: false
        })
      }
    })
  },
  /**
   * 获取砍价活动
   */
  getBargainActivity(merchantId, shopId) {
    activityModel.bargainActivityQuery({
      merchantId: merchantId,
      shopId: shopId
    }).then(res => {
      this.setData({
        bargainId: res || null
      })
    })
  }
  // judgeIsLogin(url) {
  //   if (!app.globalData.isLogin) {
  //     wx.showModal({
  //       content: '请先授权登录哦',
  //       cancelColor: '#231916',
  //       confirmText: '登录',
  //       confirmColor: '#6AB64E',
  //       success(res) {
  //         if (res.confirm) {
  //           wx.navigateTo({
  //             url: '/pages/login/index',
  //           })
  //         }
  //       }
  //     })
  //   } else {
  //     wx.navigateTo({
  //       url
  //     })
  //   }
  // }
})